package com.jing.yuntuku.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jing.yuntuku.config.UserConstant;
import com.jing.yuntuku.exception.BusinessException;
import com.jing.yuntuku.exception.ErrorCode;
import com.jing.yuntuku.model.bean.User;
import com.jing.yuntuku.model.dto.UserLoginDto;
import com.jing.yuntuku.model.dto.UserQueryDto;
import com.jing.yuntuku.model.enums.UserRoleEnum;
import com.jing.yuntuku.model.vo.UserLoginVo;
import com.jing.yuntuku.model.vo.UserVO;
import com.jing.yuntuku.service.UserService;
import com.jing.yuntuku.mapper.UserMapper;
import com.jing.yuntuku.utils.ThrowUtils;
import com.jing.yuntuku.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 18151
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-09-09 10:31:02
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 注册功能
     *
     * @param userAccount     注册账号
     * @param userPassword    注册密码
     * @param confirmpassword 校验密码
     * @return
     */
    @Override
    public Long Register(String userAccount, String userPassword, String confirmpassword) {
        //校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, confirmpassword), new BusinessException(ErrorCode.FORBIDDEN_ERROR, "参数为空"));
        ThrowUtils.throwIf(userAccount.length() < 4, new BusinessException(ErrorCode.FORBIDDEN_ERROR, "账号过短"));
        ThrowUtils.throwIf(userPassword.length() < 8 || confirmpassword.length() < 8, new BusinessException(ErrorCode.FORBIDDEN_ERROR, "密码过短"));
        //判断是否重复
        ThrowUtils.throwIf(!userPassword.equals(confirmpassword), new BusinessException(ErrorCode.FORBIDDEN_ERROR, "两次密码不一致"));

        //检查账号是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.baseMapper.selectCount(queryWrapper);

        ThrowUtils.throwIf(count > 0, new BusinessException(ErrorCode.FORBIDDEN_ERROR, "账号重复"));
        //加密密码
        String encryptPassword = UserUtils.getEncryptPassword(userPassword);

        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());

        boolean save = this.save(user);

        ThrowUtils.throwIf(!save, new BusinessException(ErrorCode.FORBIDDEN_ERROR, "注册失败，数据库错误"));
        return 0L;
    }

    /**
     * 登录接口
     *
     * @param userAccount
     * @param userPassword
     * @param request
     * @return
     */
    @Override
    public UserLoginVo login(String userAccount, String userPassword, HttpServletRequest request) {
        //校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), new BusinessException(ErrorCode.FORBIDDEN_ERROR, "参数为空"));
        ThrowUtils.throwIf(userAccount.length() < 4, new BusinessException(ErrorCode.FORBIDDEN_ERROR, "账号错误"));
        ThrowUtils.throwIf(userPassword.length() < 8, new BusinessException(ErrorCode.FORBIDDEN_ERROR, "密码错误"));

        //加密
        String encryptPassword = UserUtils.getEncryptPassword(userPassword);
        //判断登录
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);

        if (user == null) {
            log.info("登录失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "用户不存在或者密码错误");
        }
        redisTemplate.opsForValue().set((UserConstant.USER_LOGIN_STATE + request.getSession().getId()), user, 1, TimeUnit.HOURS);
        user = this.getUserLoginVo(request);
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtils.copyProperties(user, userLoginVo);
        return userLoginVo;
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    @Override
    public User getUserLoginVo(HttpServletRequest request) {
        Object redisValue = redisTemplate.opsForValue().get((UserConstant.USER_LOGIN_STATE + request.getSession().getId()));
        ThrowUtils.throwIf(redisValue == null, new BusinessException(ErrorCode.NOT_LOGIN_ERROR));
        if (redisValue instanceof User) {
            return (User) redisValue;
        }
        throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }

    /**
     * 注销
     *
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        Object redisValue = redisTemplate.opsForValue().get((UserConstant.USER_LOGIN_STATE + request.getSession().getId()));
        ThrowUtils.throwIf(redisValue == null, new BusinessException(ErrorCode.NOT_LOGIN_ERROR));
        Boolean delete = redisTemplate.delete(UserConstant.USER_LOGIN_STATE + request.getSession().getId());
        ThrowUtils.throwIf(!Boolean.TRUE.equals(delete), new BusinessException(ErrorCode.SYSTEM_ERROR, "注销失败"));
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE + request.getSession().getId());
        return true;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryDto userQueryDto) {
        if (userQueryDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryDto.getId();
        String userAccount = userQueryDto.getUserAccount();
        String userName = userQueryDto.getUserName();
        String userProfile = userQueryDto.getUserProfile();
        String userRole = userQueryDto.getUserRole();
        String sortField = userQueryDto.getSortField();
        String sortOrder = userQueryDto.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 查找用户
     *
     * @param userAccount
     * @return
     */
    @Override
    public User getUserByUserAccount(String userAccount) {
        // 1. 参数校验：若 userAccount 为空/空白字符，直接返回 null（或抛出参数异常，根据业务决定）
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount), ErrorCode.PARAMS_ERROR);

        // 2. 构建查询条件：等值查询 user_account 字段（数据库字段名，非实体类属性名）
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // eq：等值条件（参数1：数据库字段名，参数2：要匹配的值）
        queryWrapper.eq("userAccount", userAccount);
        // 补充：若表有逻辑删除（@TableLogic），MyBatis-Plus 会自动过滤 is_delete=1 的数据，无需额外加条件
        // 3. 调用 MyBatis-Plus 内置方法 getOne()：查询符合条件的唯一记录
        // getOne() 会自动处理“多条结果”的情况（默认抛出异常，若需忽略可加 queryWrapper.last("LIMIT 1")）
        return this.getOne(queryWrapper);
    }

    /**
     * 判断当前登录用户是否为管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole().equals(UserConstant.ADMIN_ROLE);
    }


}
